#include <iostream>
#include <unistd.h>
#include <cassert>
#include <sys/wait.h>
#include <sys/types.h>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>

using std::cout;
using std::endl;

// 使用匿名管道来让父子进程进行通信
int main()
{
    // 1.创建管道
    int pipefd[2] = {0};  // pipefd[0] 读端   pipefd[1] 写端
    int n = pipe(pipefd); // 成功返回0
    assert(n != -1);
    (void)n;

    // 2.创建子进程   父进程写入, 子进程读取
    pid_t id = fork();
    assert(id != -1);
    if (id == 0)
    {
        // 子进程
        close(pipefd[1]); // 关闭写端

        char buffer[1024];
        while (true)
        {
            ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if (s > 0)
            {
                buffer[s] = 0;
                cout << "child get a message[" << getpid() << "] " << "Father# " << buffer << endl;
            }
            else if (s == 0)
            {
                cout << "write quit(father), me quit" << endl;
                break;
            }
        }

        close(pipefd[0]);
        exit(0);
    }

    // 父进程
    close(pipefd[0]); // 关闭读端

    // 父进程发送数据
    std::string message = "我是父进程,我正在给你发送消息!";
    int count = 0;
    char send_buffer[1024];
    while (true)
    {
        snprintf(send_buffer, sizeof(send_buffer), "%d: %s", count++, message.c_str()); // 构建一个变化的字符串

        write(pipefd[1], send_buffer, strlen(send_buffer));

        sleep(1);
        cout << count << endl;
        if (count == 5)
        {
            cout << "father quit!" <<endl;
            break;
        }
    }
    close(pipefd[1]);

    // 进程等待
    pid_t ret = waitpid(-1, nullptr, 0);
    cout << "id:" << id << " ret:" << ret << endl;
    return 0;
}
